import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/config/global_configs.dart';
import 'package:ls_work/model/customer_info_model.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/food/scan_old_data.dart';
import 'package:ls_work/net/response/food/site_list_data.dart';
import 'package:ls_work/net/response/response_data.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/util/utils.dart';
import 'package:ls_work/viewmodel/model/combo_data_model.dart';

import '../../a_elder/models/elder_entity.dart';
import '../../a_elder/page/elder_search_page.dart';
import '../../message/message_config.dart';
import '../../model/decode_qrcode_model.dart';
import '../../model/food/food_record_model.dart';
import '../../ui/food/new_single/new_single_menu_page.dart';
import '../../ui/food/new_week/new_choose_week_menu_page.dart';
import '../../ui/food/new_week/new_regular_week_menu_page.dart';

class SingleOrderSelectPlaceViewModel extends BaseViewModel {
  final String orderType;
  final String id;
  ScanOldData? oldData;
  final String? oldId;
  final int? mealId;

  DecodeQrcodeModel model = new DecodeQrcodeModel();
  var comboModel = ComboDataModel();

  SingleOrderSelectPlaceViewModel(BuildContext context, this.orderType, this.id,
      {this.oldId, this.mealId})
      : super(context);

  CustomerInfoModel scanOldModel = new CustomerInfoModel();
  var infoModel = FoodRecordModel();

  Future<void> getSiteList() async {
    showLoadingState();
    try {
      var data = await PostRequest.getSiteList(id);
      // hideDialog();
      if ('0' == data['code'].toString()) {
        var bean = ResponseBean.fromJson(data);
        totalPlaceList = ((bean.data as List?) ?? [])
                .map((e) => SiteListData.fromJson(e))
                .toList() ??
            [];
        placeList = totalPlaceList;
        if (placeList.isNotEmpty) {
          if (placeList.isNotEmpty) {
            selectedPlace = placeList[0];
          }
          _setDateInfo();
          if (!oldId.isNullOrEmpty()) {
            initOldData();
          }
          notifyListeners();
          showContent();
        } else {
          showEmptyState(msg: '未配置场所');
        }
      } else {
        showErrorState(data['msg']);
      }
    } catch (e) {
      // hideDialog();
      showErrorState(NetErrorUtils.getNetError(e));
    }
  }

  void _setDateInfo() {
    // if (selectedPlace != null) {
    //   dateList = selectedPlace.mealDateInfo ?? [];
    //   if ((selectedPlace.mealDateInfo ?? []).isNotEmpty) {
    //     selectedDate = selectedPlace.mealDateInfo[0];
    //     _setTimeList();
    //   } else {
    //     foodTimeList = [];
    //     selectedDate = null;
    //   }
    // }

    dateList = List.generate(7, (index) {
      var now = DateTime.now();
      var date = now.add(Duration(days: index));
      return date;
    });
  }

  void _setTimeList() {
    // if (!selectedDate.sections.isNullOrEmpty()) {
    //   foodTimeList = selectedDate.sections
    //       .split(",")
    //       .map((e) => PickerDataWithIdModel(pickId: e))
    //       .toList();
    //   var strList = selectedDate.sectionsName.split(",");
    //   for (var i = 0; i < foodTimeList.length; i++) {
    //     foodTimeList[i].pickName = strList[i];
    //   }
    //   selectedFoodTime = foodTimeList[0];
    // } else {
    //   selectedFoodTime = null;
    // }
    foodTimeList = [
      PickerDataWithIdModel(pickName: "早餐", pickId: '1'),
      PickerDataWithIdModel(pickName: "午餐", pickId: '2'),
      PickerDataWithIdModel(pickName: "晚餐", pickId: '3'),
    ];
  }

  SiteListData? selectedPlace;
  List<SiteListData> placeList = [];
  List<SiteListData> totalPlaceList = [];

  ///选择食堂
  Widget selectPlaceWidget() {
    var list = (placeList ?? []).map((e) {
      return CommonText(e.name,
              textColor: e == selectedPlace ? Colors.white : Colors.grey)
          .addToContainer(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 6),
              decoration: BoxDecoration(
                  color: e == selectedPlace ? Colours.app_main : Colors.white,
                  borderRadius: 20.borderRadius,
                  border: Border.all(
                      color: e == selectedPlace
                          ? Colours.app_main
                          : Colors.grey[400]!)),
              alignment: Alignment.center,
              margin: EdgeInsets.only(right: 10))
          .onTap(() {
        selectedPlace = e;
        // _setDateInfo();
        notifyListeners();
      });
    }).toList();
    return ListView(
      children: list,
      padding: EdgeInsets.only(left: 16),
      scrollDirection: Axis.horizontal,
    ).addToContainer(height: 36);
  }

  var today = DateTime.now();
  var dateList = <DateTime>[];
  var _dateFormat = [yyyy, '-', mm, '-', dd];
  var _strFormat = [mm, '月', dd, '日'];
  DateTime? selectedDate;

  ///选择日期
  Widget selectDateWidget() {
    if (selectedPlace == null || dateList.isEmpty) {
      return Container();
    }
    var list = dateList.map((e) {
      return CommonText(e.toDateStr(_strFormat),
              textColor: e == selectedDate ? Colors.white : Colors.grey)
          .addToContainer(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 6),
              decoration: BoxDecoration(
                  color: e == selectedDate ? Colours.app_main : Colors.white,
                  borderRadius: 20.borderRadius,
                  border: Border.all(
                      color: e == selectedDate
                          ? Colours.app_main
                          : Colors.grey[400]!)),
              alignment: Alignment.center,
              margin: EdgeInsets.only(right: 10))
          .onTap(() {
        selectedDate = e;
        _setTimeList();
        notifyListeners();
      });
    }).toList();
    return ListView(
      children: list,
      padding: EdgeInsets.only(left: 16),
      scrollDirection: Axis.horizontal,
    ).addToContainer(height: 36);
  }

  List<PickerDataWithIdModel> foodTimeList = [];
  PickerDataWithIdModel? selectedFoodTime;

  ///用餐时段
  Widget selectFoodTimeWidget() {
    if (selectedPlace == null || dateList.isEmpty || foodTimeList.isEmpty) {
      return Container();
    }
    var list = foodTimeList.map((e) {
      return CommonText(e.pickName,
              textColor: e == selectedFoodTime ? Colors.white : Colors.grey)
          .addToContainer(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 6),
              decoration: BoxDecoration(
                  color:
                      e == selectedFoodTime ? Colours.app_main : Colors.white,
                  borderRadius: 20.borderRadius,
                  border: Border.all(
                      color: e == selectedFoodTime
                          ? Colours.app_main
                          : Colors.grey[400]!)),
              alignment: Alignment.center,
              margin: EdgeInsets.only(right: 10))
          .onTap(() {
        selectedFoodTime = e;
        notifyListeners();
      });
    }).toList();
    return ListView(
      children: list,
      padding: EdgeInsets.only(left: 16),
      scrollDirection: Axis.horizontal,
    ).addToContainer(height: 36);
  }

  var foodTypeList = <PickerDataWithIdModel>[];
  var foodTypeSelectList = <PickerDataWithIdModel>[];
  PickerDataWithIdModel? selectedFoodType;

  ///用餐方式
  Widget selectFoodTypeWidget() {
    var list = foodTypeList.map((e) {
      return CommonText(e.pickName,
              textColor:
                  e.name == selectedFoodType?.name ? Colors.white : Colors.grey)
          .addToContainer(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 6),
              decoration: BoxDecoration(
                  color: e.name == selectedFoodType?.name
                      ? Colours.app_main
                      : Colors.white,
                  borderRadius: 20.borderRadius,
                  border: Border.all(
                      color: e.name == selectedFoodType?.name
                          ? Colours.app_main
                          : Colors.grey[400]!)),
              alignment: Alignment.center,
              margin: EdgeInsets.only(right: 10))
          .onTap(() {
        selectedFoodType = e;
        notifyListeners();
      });
    }).toList();
    return ListView(
      children: list,
      padding: EdgeInsets.only(left: 16),
      scrollDirection: Axis.horizontal,
    ).addToContainer(height: 36);
  }

  var useNumber = 1;

  void selectUseNumber() {
    var data = List.generate(
        20,
        (index) => PickerDataWithIdModel(
            pickName: '${index + 1}人', pickId: (index + 1).toString()));
    DataPickerView(context, data, onSubmitListener: (p1, p2, p3) {
      var item = data[p1];
      useNumber = item.pickId?.toInt() ?? 0;
      notifyListeners();
    }).show();
  }

  var selectedWeekTime = '1';

  var orderTimes = [
    PickerDataWithIdModel(pickName: '本周', pickId: '1'),
    PickerDataWithIdModel(pickName: '下周', pickId: '2'),
    PickerDataWithIdModel(pickName: '下下周', pickId: '3'),
  ];

  ///选择周
  Widget selectWeekTime() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: orderTimes
          .map((e) => Row(
                children: [
                  Icon(
                    selectedWeekTime == e.pickId
                        ? Icons.radio_button_checked_sharp
                        : Icons.radio_button_off,
                    color: selectedWeekTime == e.pickId
                        ? Colours.app_main
                        : Colors.grey,
                  ),
                  Container(
                    width: 8,
                  ),
                  CommonText(e.pickName, textSize: 15)
                ],
              ).onTap(() {
                selectedWeekTime = e.pickId ?? "";
                notifyListeners();
              }))
          .toList(),
    ).addToContainer(margin: EdgeInsets.symmetric(horizontal: 16));
  }

  Widget selectOldWidget() {
    return Column(
      children: [
        Row(
          children: [
            CommonText(
              '选择老人',
            ),
            CommonText(oldData?.selectedOldName ?? "",
                    hintText: '选择老人或者扫码', textAlign: TextAlign.right)
                .onTap(() async {
              ElderInfo? old = await Go().push(ElderSearchPage(
                needBack: true,
                isSelected: false,
              ));

              if (old != null) {
                oldData = await getOldData(old.id.toString());
                onGetOldInfo();
                notifyListeners();
              }
            }).setWeight(1),
            Container(
              width: 10,
            ),
            Icon(Icons.qr_code_scanner).onTap(() async {
              var code = await Utils.scan();
              if (!code.isNullOrEmpty()) {
                _scanResult(code);
              }
            })
          ],
        ),
        oldData == null || oldData?.limitData == null
            ? Container()
            : CommonText(oldData?.limitData?.packageConfName)
                .addToContainer(alignment: Alignment.centerRight)
      ],
    ).addToContainer(
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12));
  }

  Future<void> _scanResult(String code) async {
    showLoadingDialog();
    try {
      var data = await model.decoed(code);
      hideDialog();
      if (data.typeCode == 1) {
        oldData = await getOldData(data.id.toString());
        notifyListeners();
      } else {
        showToast("请扫描长者二维码");
      }
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  Future<ScanOldData?> getOldData(String scanCode) async {
    showLoadingDialog();
    try {
      var data = await scanOldModel.getOldData(scanCode);
      hideDialog();
      return data;
    } catch (e) {
      hideDialog();
      showToast(e.toNetError());
      return null;
    }
  }

  void nextStep() {
    if (oldData == null) {
      showToast('请选择用餐长者');
      return;
    }
    if (selectedPlace == null) {
      showToast('请选择场所');
      return;
    }
    if (orderType == '1') {
      if (selectedDate == null) {
        showToast('请选择用餐日期');
        return;
      }
      if (selectedFoodTime == null) {
        showToast('请选择用餐时段');
        return;
      }

      // Go().push(SingleFoodMenuPage(
      //   orderType: id,
      //   date: selectedDate.toDateStr(_dateFormat),
      //   siteId: selectedPlace,
      //   foodTime: selectedFoodTime,
      //   useNumber: useNumber,
      //   userWay: selectedFoodType,
      // ));
      Go().push(NewSingelMenuPage(
        orderType: id,
        date: selectedDate?.toDateStr(_dateFormat) ?? "",
        siteId: selectedPlace!,
        foodTime: selectedFoodTime!,
        useNumber: useNumber,
        userWay: selectedFoodType!,
        humanOldId: oldData!.elderHumanId!,
      ));
    } else {
      if (oldData == null) {
        showToast('请选择用餐长者');
        return;
      }
      // Go().push(WeekMenuPage(
      //     time: selectedWeekTime,
      //     siteId: selectedPlace.id.toString(),
      //     older: selectedOld,orderModelType: orderType,));
      // Go().push(RegularWeekMenuPage(
      //   time: selectedWeekTime,
      //   siteId: selectedPlace.id.toString(),
      //   older: selectedOld,
      //   orderModelType: orderType,
      // ));
      getWeekMenuType();
    }
  }

  Future<void> getWeekMenuType() async {
    showLoadingDialog();
    try {
      var data = await PostRequest.weekMenu(selectedWeekTime,
          selectedPlace?.id.toString(), oldData?.selectOldId.toString(), id);
      hideDialog();
      if ('0' == data['code'].toString()) {
        if (data['data'] == null || data['data']['menuJson'] == null) {
          showToast('该场所未配置周菜单');
          return;
        }
        var type = data['data']['menuJson']["weekMenuModel"].toString();
        if (type == "1") {
          // Go().push(RegularWeekMenuPage(
          //   time: selectedWeekTime,
          //   siteId: selectedPlace.id.toString(),
          //   oldData: oldData,
          //   orderModelType: id,
          //   useType: selectedFoodType,
          // ));
          Go().push(NewRegularWeekMenuPage(
            time: selectedWeekTime,
            siteId: selectedPlace?.id.toString() ?? "",
            oldData: oldData,
            orderModelType: id,
            useType: selectedFoodType,
          ));
        } else {
          // Go().push(WeekMenuPage(
          //   time: selectedWeekTime,
          //   siteId: selectedPlace.id.toString(),
          //   oldData: oldData,
          //   orderModelType: id,
          //   useType: selectedFoodType,
          // ));
          Go().push(NewChooseWeekMenuPage(
            time: selectedWeekTime,
            siteId: selectedPlace?.id.toString() ?? "",
            oldData: oldData,
            orderModelType: id,
            useType: selectedFoodType,
          ));
        }
      } else {
        showToast(data['msg'].toString());
      }
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  @override
  void onCreated() {
    super.onCreated();
    initData();
    initFoodType();
  }

  void initFoodType() {
    var type = orderType == '1' ? 1 : 0;
    if (type == 0) {
      foodTypeSelectList = <PickerDataWithIdModel>[
        PickerDataWithIdModel(pickName: '堂食', pickId: '1'),
        PickerDataWithIdModel(pickName: '配送', pickId: '2'),
      ];
    } else {
      foodTypeSelectList = [
        PickerDataWithIdModel(pickName: '堂食', pickId: '1'),
        PickerDataWithIdModel(pickName: '包装', pickId: '2'),
        PickerDataWithIdModel(pickName: '包厢', pickId: '3')
      ];
    }
    foodTypeList = foodTypeSelectList;

    if (selectedFoodType == null) {
      selectedFoodType = foodTypeList[0];
    }
  }

  Future<void> initData() async {
    getShowPriceValue();
    await getSiteList();
    await getMealInfoData();
  }

  Future<void> getShowPriceValue() async {
    var list = await comboModel.getComboData(ComboDataModel.showPrice);
    if (BuildConfig.isDebug) {
      GlobalConfigs.showPayPrice = true;
    } else {
      GlobalConfigs.showPayPrice = list.isEmpty;
    }
  }

  Future<void> initOldData() async {
    oldData = await getOldData(oldId!);
    onGetOldInfo();
    notifyListeners();
  }

  Future<void> getMealInfoData() async {
    if (mealId != null) {
      try {
        var data = await infoModel.weekOrderInfo(mealId.toString());
        hideDialog();
        selectedWeekTime = data.time.toString();
        for (var type in foodTypeList) {
          if (type.pickId == data.useType) {
            selectedFoodType = type;
            break;
          }
        }
        for (var place in placeList) {
          if (place.id.toString() == data.siteId) {
            selectedPlace = place;
            break;
          }
        }
        notifyListeners();
      } catch (e) {
        showToast(NetErrorUtils.getNetError(e));
        hideDialog();
      }
    }
  }

  void onGetOldInfo() {
    if (oldData != null) {
      if (oldData!.bindSiteId != null) {
        placeList = totalPlaceList
            .where((element) => element.id == oldData!.bindSiteId)
            .toList();
      } else {
        placeList = totalPlaceList;
      }
      if (placeList.isNotEmpty) {
        selectedPlace = placeList[0];
      }

      if (oldData?.bindUseType != null) {
        foodTypeList = foodTypeSelectList
            .where(
                (element) => element.pickId == oldData!.bindUseType.toString())
            .toList();
        print(foodTypeList.map((e) => e.name).toString());
      } else {
        foodTypeList = foodTypeSelectList;
      }
      if (foodTypeList.isNotEmpty) {
        selectedFoodType = foodTypeList[0];
      }
      notifyListeners();
    }
  }

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if (event.msgCode == MessageConfig.NFC_READ_IC_CARD) {
      var cardNumber = event.obj as String;
      getCustomerByCard(cardNumber);
    }
  }

  Future<void> getCustomerByCard(String cardNumber) async {
    showLoadingDialog();
    try {
      var old = await scanOldModel.getCardAccount(physicalCardNo: cardNumber);
      if(old.data!=null){
        oldData = await getOldData(old.data!.human!.id.toString());
        onGetOldInfo();
        notifyListeners();
      }else{
        showToast("未查询到卡信息");
      }

      hideDialog();
    } catch (e) {
      showToast(e.toNetError());
      hideDialog();
    }
  }
}

class SelectDateData {
  final String? dateStr;
  final String? date;

  SelectDateData({this.dateStr, this.date});

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is SelectDateData &&
          runtimeType == other.runtimeType &&
          date == other.date;

  @override
  int get hashCode => date.hashCode;
}
